from django.core.management.base import BaseCommand, CommandError
from optparse import make_option

from django.conf import settings
from django.db import connection, models
from time import strftime
import time

from djfacet.constants import *
from djfacet.facetviews import *
from djfacet.fb_utils.utils import djfacetlog

##################
#  2010-09-17 
#  TEST 
#
##################



# EG:
# bash-3.2$ python manage.py djfacet_deletecache surname



class Command(BaseCommand):
	args = '<facet_uniquename1, facet_uniquename2, facet_uniquename3 etc. >'
	help = 'Delete cachedObject according to parameters'

	# make_option requires options in optparse format
	option_list = BaseCommand.option_list  + (
						make_option('--resulttypes', action='store', dest='resulttypes', default='all',
									help='The _resulttypes_ option determines what resulttypes-facet couple will be cached'),
						make_option('--emptyunused', action='store', dest='emptyunused', default='no',
									help='The _emptyunused_ option empties the unused elements from CachedFacetValue and CachedQueryArgs tables'),
						make_option('--firstlevel', action='store', dest='firstlevel', default='no',
									help='The _firstlevel_ option determines whether we delete only objects at the firstlevel (= with no QueryArgs)'),
						make_option('--secondlevel', action='store', dest='secondlevel', default='no',
									help='The _secondlevel_ option determines whether to delete only objects at the firstlevel (= with QueryArgs)'),
				  )


	# :an init method that does the repetitive stuff....
	def __init__(self, *args, **kwargs):
		
		loaded_facet_groups = []
		facets_for_template = []

		# load facet specs 
		# 1: create groups from SPECS.facet_groups	
		for x in reversed(sorted(DJ_SPECS.facet_groups, key=lambda (k): k['position'])):
			if x['default']:
				loaded_facet_groups.append(FacetsGroup(x['uniquename'], x['label'], x['position'])) 
				
		# 2: load facets into groups using SPECS.facetslist				
		for g in loaded_facet_groups:
			g.buildfacets_fromspecs(DJ_SPECS.facetslist)
		
		# 3: load result types
		self.result_types = DJ_SPECS.result_types 

		# initialize the faceted manager
		self.fm = FacetedManager(loaded_facet_groups, self.result_types)
		# self.fm.init_resulttypes_activeIDs()	 #cache this in memory first.
		
		super(Command, self).__init__(*args, **kwargs)
	


	def handle(self, *args, **options): 
		"""
		args - args (eg. myapp in "manage.py reset myapp") = the facet names [result types are all by default]
		options - configurable command line options
		"""

		all_facets = self.fm.get_all_facets()
		all_resulttypes = self.result_types
		if not all_facets:
			raise "No facets available!" 
			
	
		if args:
			temp = []
			for a in args:
				djfacetlog("Argument provided: ==%s==" % str(a))
				temp += [x for x in all_facets if x.uniquename == str(a)]
			all_facets = temp

		if options['resulttypes'] != 'all':
			test = self.fm.get_resulttype_from_name(options['resulttypes'])
			if test:
				all_resulttypes = [test]

		# feedback:
		print "\n\n++ = ++ = ++ = ++ = ++ = ++ = ++ = ++\nSTARTED DELETING CACHED FACET VALUES WITH PARAMS:"	
		print "facets: " + str([facet.uniquename for facet in all_facets])
		print "resulttypes:  "  + str([resulttype['uniquename'] for resulttype in all_resulttypes])
		print "firstlevel:  "  + str(options['firstlevel'])
		print "secondlevel:  "  + str(options['secondlevel'])
		print "emptyunused:  "  + str(options['emptyunused'])
		print "++ = ++ = ++ = ++ = ++ = ++ = ++ = ++\n"


		
		#  now do the actions: 

		cacheDBinstance = DbCache(self.fm)

		if options['emptyunused'] == 'yes':
			print '.... now deleting all the unused elements...'
			tot = cacheDBinstance._emptyUnusedElements()
			print '\nSuccessfully deleted [%d] unused elements' % tot
			return True

		if options['firstlevel'] == 'yes':
			for facet in all_facets:
				for r in all_resulttypes:
					cacheDBinstance._emptyCacheForFacetQuery(facet, r, None)
			print '\nSuccessfully deleted firstlevel facets'
			print '.... now deleting other unused elements...'
			tot = cacheDBinstance._emptyUnusedElements()
			print '\nSuccessfully deleted [%d] unused elements' % tot
			return True

		if options['secondlevel'] == 'yes':
			for facet in all_facets:
				for r in all_resulttypes:
					cacheDBinstance._emptyCacheForFacetQuery(facet, r, 'only_with_queryargs')
			print '\nSuccessfully deleted secondlevel facets'
			print '.... now deleting other unused elements...'
			tot = cacheDBinstance._emptyUnusedElements()
			print '\nSuccessfully deleted [%d] unused elements' % tot
			return True
							
		if options['firstlevel'] == 'no' and options['secondlevel'] == 'no':
			for facet in all_facets:
				for r in all_resulttypes:
					cacheDBinstance._emptyCacheForFacetQuery(facet, r, 'all')
			print '\nSuccessfully deleted ALL cached facets (WITH or WITHOUT QUERYARGS)'
			print '.... now deleting other unused elements...'
			tot = cacheDBinstance._emptyUnusedElements()
			print '\nSuccessfully deleted [%d] unused elements' % tot
			return True
			
	
